//
//  WBBaseViewController.swift
//  新浪微博
//
//  Created by ZJ on 2017/10/10.
//  Copyright © 2017年 zj. All rights reserved.
//

import UIKit

/// 所有主控制器的基本控制器
class WBBaseViewController: UIViewController {

//    var userLogon = true
    
    var visitorInfoDictionary: [String: String]?
    
    var tableView: UITableView?
    var refreshControl: UIRefreshControl?
    
    var isPullup = false
    
    lazy var navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 64))
    lazy var navItem = UINavigationItem()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        WBNetworkManager.shared.userLogon ? loadData() : ()
        
        //
        NotificationCenter.default.addObserver(self, selector: #selector(loginSuccess(n:)), name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override var title: String? {
        didSet {
            navItem.title = title
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @objc func loadData() {
        // 如果子类不实现任何方法，默认关闭刷新控件
        refreshControl?.endRefreshing()
    }
    
    func setupTableView() {
        tableView = UITableView.init(frame: view.bounds, style: UITableViewStyle.plain)
        
        view.insertSubview(tableView!, belowSubview: navigationBar)
        
        tableView?.dataSource = self
        tableView?.delegate = self
        
        // 设置内容缩进
        tableView?.contentInset = UIEdgeInsetsMake(navigationBar.bounds.height, 0, tabBarController?.tabBar.bounds.height ?? 49, 0)
        
        // 修改指示器的缩进
        tableView?.scrollIndicatorInsets = tableView!.contentInset
        
        // 设置刷新控件
        refreshControl = UIRefreshControl()
        
        tableView?.addSubview(refreshControl!)
        
        refreshControl?.addTarget(self, action: #selector(loadData), for: UIControlEvents.valueChanged)
    }
}

extension WBBaseViewController {
    @objc private func loginSuccess(n: Notification) {
        print("登录成功 \(n)")
        
        navItem.leftBarButtonItem = nil
        navItem.rightBarButtonItem = nil
        
        // 需要重新设置 view
        view = nil
        
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc private func login() {        
        // 发送通知
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
    }
    
    @objc private func register() {
        print("用户注册")
    }
}

// MARK: - 设置界面
extension WBBaseViewController {
    private func setupVisitorView() {
        let visitorView = WBVisitorView(frame: view.bounds)
                
        view.insertSubview(visitorView, belowSubview: navigationBar)
        visitorView.visitorInfo = visitorInfoDictionary
        
        //add 按钮的监听方法 （代理解耦合）
        visitorView.loginButton.addTarget(self, action: #selector(login), for: .touchUpInside)
        visitorView.registerButton.addTarget(self, action: #selector(register), for: .touchUpInside)
        
        //设置导航条按钮
        navItem.leftBarButtonItem = UIBarButtonItem.init(title: "注册", style: .plain, target: self, action: #selector(register))
        navItem.rightBarButtonItem = UIBarButtonItem.init(title: "登录", style: .plain, target: self, action: #selector(login))
    }
    
    private func setupUI() {
        view.backgroundColor = UIColor.white
        
        // 取消自动缩进 - 如果隐藏导航栏，会缩进 20 个点
        automaticallyAdjustsScrollViewInsets = false
        
        setupNavigationBar()
        WBNetworkManager.shared.userLogon ? setupTableView() : setupVisitorView()
    }
    
    private func setupNavigationBar() {
        view.addSubview(navigationBar)
        navigationBar.items = [navItem]
        // 设置整个背景颜色
        navigationBar.barTintColor = UIColor.init(red: 0xf6, green: 0xf6, blue: 0xf6, alpha: 1.0)
        // 中间标题
        navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.darkGray]
        // 设置系统按钮文字渲染颜色
        navigationBar.tintColor = UIColor.orange
    }
}

// MARK: - UITableViewDelegate, UITableViewDataSource
extension WBBaseViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return UITableViewCell()
    }
    
    ///
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        let row = indexPath.row
        let section = tableView.numberOfSections - 1
        
        if row < 0 || section < 0 {
            return
        }
        
        let count = tableView.numberOfRows(inSection: section)
        if (row == count - 1) && !isPullup {
            print("上拉刷新")
            isPullup = true
            
            loadData()
        }
    }
}
